import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'log.dart';

mixin CommonApi {
  Future<dynamic> commonApiGet(GetConnect getConnect, String url,
      {Map<String, String>? headers,
      String? contentType,
      Map<String, dynamic>? query,
      bool showFullLog = false}) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Log.debug(
        'ApiGet Start Url=${url.toString()} AuthToken=${_authtoken.toString()}');
    Map<String, String>? tempHeaders = <String, String>{
      "authtoken": _authtoken,
      'content-type': 'application/json;charset=UTF-8'
    };
    final response = await getConnect.get(url, headers: tempHeaders);
    Log.debug(
        'ApiGet End StatusCode=${response.statusCode} Url=${url.toString()}');
    Log.debug('ApiGet End Response=${response.bodyString}',
        showFullLog: showFullLog);
    return response;
  }

  Future<dynamic> commonApiPost(GetConnect getConnect, String url,
      {dynamic jsonData,
      Map<String, String>? headers,
      String? contentType,
      Map<String, dynamic>? query,
      bool showFullLog = false}) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Log.debug(
        'ApiPost Start Url=${url.toString()} AuthToken=${_authtoken.toString()}');
    Log.debug('ApiPost Start RequestBody=${jsonData.toString()}');
    Map<String, String>? tempHeaders = <String, String>{
      "authtoken": _authtoken,
      'content-type': 'application/json;charset=UTF-8'
    };
    var response = await getConnect.post(
      url,
      jsonData,
      headers: tempHeaders,
    );
    Log.debug(
        'ApiPost End StatusCode=${response.statusCode} Url=${url.toString()}');
    if (showFullLog) Log.debug('ApiPost End Response=${response.bodyString}');
    return response;
  }

  Future<dynamic> commonApiPut(GetConnect getConnect, String url,
      {dynamic jsonData,
      Map<String, String>? headers,
      String? contentType,
      Map<String, dynamic>? query,
      bool showFullLog = false}) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Log.debug(
        'ApiPut Start Url=${url.toString()} AuthToken=${_authtoken.toString()}');
    Log.debug('ApiPut Start RequestBody=${jsonData.toString()}');
    Map<String, String>? tempHeaders = <String, String>{
      "authtoken": _authtoken,
      'content-type': 'application/json;charset=UTF-8'
    };
    var response = await getConnect.put(
      url,
      jsonData,
      headers: tempHeaders,
    );
    Log.debug(
        'ApiPut End StatusCode=${response.statusCode} Url=${url.toString()}');
    if (showFullLog) Log.debug('ApiPut End Response=${response.bodyString}');
    return response;
  }
}
